{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Tutorial 1: Bases and Domains"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**Overview:** This tutorial covers the basics of setting up and interacting with basis and domain objects in Dedalus.\n",
    "Dedalus uses spectral discretizations to represent fields and solve PDEs.\n",
    "These discretizations are specified by selecting a spectral basis for each spatial dimension, and combining them to form a domain.\n",
    "When running in parallel, domains are automatically distributed using a block decomposition."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import matplotlib.pyplot as plt\n",
    "from dedalus import public as de"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "%matplotlib inline"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.1: Bases"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Creating a basis"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each type of basis in Dedalus is represented by a separate class.\n",
    "These classes define the corresponding spectral operators and transforms between the \"grid space\" and \"coefficient space\" representations of functions in that basis.\n",
    "The most commonly used bases are:\n",
    "\n",
    "* `Fourier` for periodic functions on an interval.\n",
    "* `SinCos` for functions with definite parity (even or odd symmetry) around the endpoints of an interval.\n",
    "* `Chebyshev` for general functions on an interval.\n",
    "\n",
    "When instantiating one of these bases, you provide a name for the spatial dimension, the number of modes, and the endpoints of the basis interval.\n",
    "Optionally, you can specify a dealiasing scale factor, indicating how much to pad the included modes when transforming to grid space.\n",
    "To properly dealias quadratic nonlinearities, for instance, you would need a scaling factor of 3/2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "xbasis = de.Chebyshev('x', 32, interval=(0,1), dealias=3/2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Other less commonly used bases include:\n",
    "\n",
    "* `Legendre` for general functions on an interval (but without fast transforms).\n",
    "* `Hermite` for decaying functions on the real line.\n",
    "* `Laguerre` for decaying functions on the half-line.\n",
    "\n",
    "See the [basis.py API documentation](https://dedalus-project.readthedocs.io/en/latest/autoapi/dedalus/core/basis/index.html) for more information about using these other bases."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Basis grids and scale factors"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Each basis has a corresponding grid that can be used for tasks like initializing and plotting fields.\n",
    "The global (non-distributed) grid of a basis can be accessed using the basis object's `grid` method, where you'll have to pass a scale factor determining the number of points in the grid, relative to the number of basis modes.\n",
    "Let's look at the Chebyshev grids with scaling factors of 1 and 3/2."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAj8AAABVCAYAAACmXIUiAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy86wFpkAAAACXBIWXMAAAsTAAALEwEAmpwYAAALuElEQVR4nO3dXYycdRXH8d/ZnW7ZRWAbSy19gUVSChRoAyslBknFEIQbJOHCSEpCuDFG45XBeKEX3mi8McYYYpAYiJELBMREJU1IRYMUd7X0DSsF7SukVltKuqXLzh4vnpl1dnZm9nl2nreZ//eTTDLz/M8585/555n/6bxszd0FAAAQioGiJwAAAJAnmh8AABAUmh8AABAUmh8AABAUmh8AABCUSpLglStX+tjYWEZTAQAASM/k5OQpd7+8+Xii5mdsbEwTExPpzQoAACAjZna41XE+9gIAAEGh+QEAAEGh+QEAAEGh+QEAAEGh+QEAAEGh+QEAAEGh+QEAAEGh+QEAAEGh+QEAAEFJ9Bees1Sdde08eFL7T5zV9asvkUx6890PtGnNpdq2cZUkzY3Xjw0O2ILc5rFW9dvFdBPfbV5a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Kek5Sdv5F2xuFl0Xd7/a3cfcfUzSs5K+QuOTqTivX7+W9Bkzq5jZiKStkt7MeZ6hibMuRxS9Gycz+4SkjZLeyXWWaFbIXl/IOz/uPmNmX5X0kqJv6D/p7vvN7Mu18ccV/WrlPkmHJE0p6tiRkZhr8m1JH5f0k9q7DDPO/5ScqZjrghzFWRN3f9PMfi9pj6RZSU+4e8uf+iIdMc+V70r6uZntVfRxy2PufqqwSQfAzH4paZuklWZ2TNJ3JC2Tit3r+e8tAABAUPgLzwAAICg0PwAAICg0PwAAICg0PwAAICg0PwAAICg0PwAAICg0PwAAICj/A69fiobUIba5AAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 720x72 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "grid_normal = xbasis.grid(scale=1)\n",
    "grid_dealias = xbasis.grid(scale=3/2)\n",
    "\n",
    "plt.figure(figsize=(10, 1))\n",
    "plt.plot(grid_normal, 0*grid_normal+1, 'o', markersize=5)\n",
    "plt.plot(grid_dealias, 0*grid_dealias-1, 'o', markersize=5)\n",
    "plt.ylim([-2, 2])\n",
    "plt.gca().yaxis.set_ticks([]);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Note that the Chebyshev grids are non-equispaced: the grid points cluster quadratically towards the ends of the interval, which can be very useful for resolving sharp features like boundary layers."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Compound bases"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "It may be useful to add resolution at a particular intermediate position in an interval.\n",
    "In this case, a compound basis consisting of stacked Chebyshev segments (or other polynomial basis segments) can be constructed simply by grouping a set of individual bases defined over adjacent intervals into a `Compound` basis object."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "xb1 = de.Chebyshev('x1', 16, interval=(0,2))\n",
    "xb2 = de.Chebyshev('x2', 32, interval=(2,8))\n",
    "xb3 = de.Chebyshev('x3', 16, interval=(8,10))\n",
    "xbasis = de.Compound('x', (xb1, xb2, xb3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Since we use the interior roots grid for the Chebyshev polynomials, the grid of the compound bases is simply the union of the subbasis grids.  When solving a problem with Dedalus, the continuity of fields across the subbasis interfaces is automatically enforced."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "image/png": "iVBORw0KGgoAAAANSUhEUgAAAj8AAABVCAYAAACmXIUiAAAAOXRFWHRTb2Z0d2FyZQBNYXRwbG90bGliIHZlcnNpb24zLjMuMCwgaHR0cHM6Ly9tYXRwbG90bGliLm9yZy86wFpkAAAACXBIWXMAAAsTAAALEwEAmpwYAAAJk0lEQVR4nO3dW2xcVxXG8W+NHSdOc0VJWnKhblGUNk1pWqxSQKCo5aFcRHhBAomoVH2kUBASKrzwygNCIIGQUNOLoCpCoVIrhLioJYKngHORcmuUKiUXO2CnJLaVhDj2LB5mJpk5PTGemTNnb2n/fy+xz97n7KW9ZtYsz5lRzN0FAACQikroAAAAAMpE8wMAAJJC8wMAAJJC8wMAAJJC8wMAAJLS387kNWvW+NDQUI9CAQAAKM7+/fsvuPva7PG2mp+hoSGNjIwUFxUAAECPmNnpvOPc9gIAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEmh+QEAAEnpDx1Aw1zVtffEuA6PTqpadVUqpvs3rNQnNq/V305O6OjYlO5bv0I7tqyTJO09Md5yrK9iLdfJG8uu1e2coucVda35xvPGsvvZ2PPDo5Oanavq9LuXNTE9o9tXLtFntt2hSsV0/Px0y9zsW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DMlOSXdJWi/pNjP7StioEItYmp9zkjY1/b5RvD0ZBTNbpFrj87K7vxo6Hujjkj5vZv9U7fbwo2b2q7AhQbUads7dG++M7lGtGUI4n5L0jrtPuPt1Sa9K+ljgmHDTv83s/ZJU/3e8zMVjaX7+IWmzmd1lZgOqfSjt9cAxJc/MTLXPMBx39x+FjgeSu3/X3Te6+5Bqz5M33Z2/ZgNz939JOmtmW+qHHpN0LGBIqN3uesTMltZr2WPiQ+gxeV3SE/Wfn5D0WpmL95e52K24+6yZPS3pj6p9Iv95dz8aOCzU3mXYJemwmR2qH/ueu/8+XEhAtL4u6eX6H3CnJD0ZOJ6kufs+M9sj6YBq31w9KP6biyDM7BVJOyStMbNzkr4v6QeSfmNmT6nWqH6x1Jj47y0AAEBKYrntBQAAUAqaHwAAkBSaHwAAkBSaHwAAkBSaHwAAkBSaHwAAkBSaHwAAkJT/AXMzEctgMlieAAAAAElFTkSuQmCC\n",
      "text/plain": [
       "<Figure size 720x72 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "compound_grid = xbasis.grid(scale=1)\n",
    "\n",
    "plt.figure(figsize=(10, 1))\n",
    "plt.plot(compound_grid, 0*compound_grid, 'o', markersize=5)\n",
    "plt.gca().yaxis.set_ticks([]);"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.2: Domains"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Creating a domain"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "`Domain` objects represent physical domains which are discretized by the direct product of a set of bases.  To build a domain, we pass a list of the composite bases, specify the (grid space) datatype, and optionally specify a process mesh for parallelization.  Let's construct a domain representing a 3D slab that is periodic in the x and y directions, and non-periodic in z."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "xbasis = de.Fourier('x', 32, interval=(0,2), dealias=3/2)\n",
    "ybasis = de.Fourier('y', 32, interval=(0,2), dealias=3/2)\n",
    "zbasis = de.Chebyshev('z', 32, interval=(0,1), dealias=3/2)\n",
    "domain = de.Domain([xbasis, ybasis, zbasis], grid_dtype=np.complex128)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Dedalus currently supports explicit computations on arbitrary N-dimensional domains.\n",
    "However, to solve PDEs with Dedalus, the first (N-1) dimensions of the domain must be separable, meaning that the linear parts of the PDE do not couple different modes in these dimensions.\n",
    "In most cases, this means the first (N-1) dimensions of the domain need to be either `Fourier` or `SinCos` bases."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Parallelization & process meshes"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "When running in an MPI environment, Dedalus uses block-distributed domain decompositions to parallelize computation.\n",
    "By default, problems are distributed across a 1-dimensional mesh of all the available MPI processes (i.e. a \"slab\" decomposition).\n",
    "However, arbitrary (N-1)-dimensional process meshes (i.e. \"pencil\" decompositions) can be used by specifying a mesh shape with the `mesh` keyword when instantiating a domain.\n",
    "The current MPI environment must have the same number of processes as the product of the mesh shape."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Layouts"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The domain object builds the machinery necessary for the parallelized allocation and transformation of fields.  This includes an ordered set of `Layout` objects describing the necessary transform/distribution states of the data between coefficient space and grid space.\n",
    "Subsequent layouts are connected by basis transforms, which must be performed locally, and global transposes (rearrangements of the data distribution across the process mesh) to achieve the required locality.\n",
    "\n",
    "The general algorithm starts from coefficient space (layout 0), with the last axis local (non-distributed).\n",
    "It proceeds towards grid space by transforming the last axis into grid space (layout 1).\n",
    "Then it globally transposes the data (if necessary) such that the penultimate axis is local, transforms that axis into grid space, etc., until all axes have been transformed to grid space (the last layout).\n",
    "\n",
    "Let's examine the layouts for the domain we just constructed.\n",
    "For serial computations such as this, no global transposes are necessary (all axes are always local), and the paths between layouts consist of coefficient-to-grid transforms, backwards from the last axis:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Layout 0:  Grid space: [False False False]  Local: [ True  True  True]\n",
      "Layout 1:  Grid space: [False False  True]  Local: [ True  True  True]\n",
      "Layout 2:  Grid space: [False  True  True]  Local: [ True  True  True]\n",
      "Layout 3:  Grid space: [ True  True  True]  Local: [ True  True  True]\n"
     ]
    }
   ],
   "source": [
    "for layout in domain.distributor.layouts:\n",
    "    print('Layout {}:  Grid space: {}  Local: {}'.format(layout.index, layout.grid_space, layout.local))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To see how things work for a distributed simulation, we'll change the specified process mesh shape and rebuild the layout objects, circumventing the internal checks on the number of available processes, etc.\n",
    "\n",
    "**Note this is for demonstration only... messing with these attributes will generally break things.**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Don't do this. For illustration only.\n",
    "domain.distributor.mesh = np.array([4, 2])\n",
    "domain.distributor.coords = np.array([0, 0])\n",
    "domain.distributor._build_layouts(domain, dry_run=True)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Layout 0:  Grid space: [False False False]  Local: [False False  True]\n",
      "Layout 1:  Grid space: [False False  True]  Local: [False False  True]\n",
      "Layout 2:  Grid space: [False False  True]  Local: [False  True False]\n",
      "Layout 3:  Grid space: [False  True  True]  Local: [False  True False]\n",
      "Layout 4:  Grid space: [False  True  True]  Local: [ True False False]\n",
      "Layout 5:  Grid space: [ True  True  True]  Local: [ True False False]\n"
     ]
    }
   ],
   "source": [
    "for layout in domain.distributor.layouts:\n",
    "    print('Layout {}:  Grid space: {}  Local: {}'.format(layout.index, layout.grid_space, layout.local))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can see that there are now two additional layouts, corresponding to the transposed states of the mixed-transform layouts.\n",
    "Two global transposes are necessary here in order for the $y$ and $x$ axes to be stored locally, which is required to perform the respective basis transforms.\n",
    "Here's a sketch of the data distribution in the different layouts:\n",
    "\n",
    "<img src=\"fig_layouts_fold.png\" width=\"800px\">"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Interacting with the layout objects directly is typically not necessary, but being aware of this system for controlling the distribution and tranformation state of data is important for interacting with field objects, as we'll see in future notebooks."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Distributed grid and element arrays"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "To help with creating field data, Dedalus domain objects provide properly oriented arrays representing the local portions of the basis grids and elements (wavenumbers or polynomial indices).\n",
    "The local grids (distributed according to the last layout, grid space) are accessed using the `domain.grid` method and specifying an axis and scale factors:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Local x shape: (32, 1, 1)\n",
      "Local y shape: (1, 8, 1)\n",
      "Local z shape: (1, 1, 16)\n"
     ]
    }
   ],
   "source": [
    "local_x = domain.grid(0, scales=1)\n",
    "local_y = domain.grid(1, scales=1)\n",
    "local_z = domain.grid(2, scales=1)\n",
    "print('Local x shape:', local_x.shape)\n",
    "print('Local y shape:', local_y.shape)\n",
    "print('Local z shape:', local_z.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The local x grid is the full Fourier grid for the x-basis, and will be the same on all processes, since the first axis is local in grid space.\n",
    "The local y and local z grids will generally differ across processes, since they contain just the local portions of the y and z basis grids, distributed across the specified process mesh (4 blocks in y and 2 blocks in z).\n",
    "\n",
    "The local elements (distributed according to layout 0) are accessed using the `domain.elements` method and specifying an axis:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Local kx shape: (8, 1, 1)\n",
      "Local ky shape: (1, 16, 1)\n",
      "Local nz shape: (1, 1, 32)\n"
     ]
    }
   ],
   "source": [
    "local_kx = domain.elements(0)\n",
    "local_ky = domain.elements(1)\n",
    "local_nz = domain.elements(2)\n",
    "print('Local kx shape:', local_kx.shape)\n",
    "print('Local ky shape:', local_ky.shape)\n",
    "print('Local nz shape:', local_nz.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The local kx and local ky elements will now differ across processes, since they contain just the local portions of the x and y wavenumbers, which are distributed in coefficient space.\n",
    "The local nz elements are the full set of Chebyshev modes, which are always local in coefficient space.\n",
    "\n",
    "These local arrays can be used to form parallel-safe initial conditions for fields, in grid or coefficient space, as we'll see in the next notebook."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python [conda env:dedalus_openblas]",
   "language": "python",
   "name": "conda-env-dedalus_openblas-py"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 1
}
